package com.yasha.sharingnews;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.yasha.control.NewsController;
import com.yasha.model.News;
import com.yasha.ulti.Tools;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class PostActivity extends Activity {

	private Spinner sp_topic_choice,sp_city_choice;
	private Button btn_browser , btn_submit ; 
	private TextView txt_city;
	private EditText edit_title , edit_phone , edit_content;
	
	private float longti=0;
	private float lati=0;
	private String topic="";
	private String city ="";
	private String imgFilePath="";
	
	private static int RESULT_LOAD_IMAGE = 1;
    private NewsController newsController;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_post);

		sp_topic_choice = (Spinner) findViewById(R.id.list_topic_choice);
		btn_browser = (Button) findViewById(R.id.btn_post_choice);
		btn_submit = (Button) findViewById(R.id.btn_post_submit);
		sp_city_choice  = (Spinner) findViewById(R.id.list_city_choice);
		edit_content = (EditText) findViewById(R.id.edit_content);
		edit_phone = (EditText) findViewById(R.id.edit_phone);
		edit_title = (EditText) findViewById(R.id.edit_title);
		
		String phoneString = Tools.loadSavedPreferences(PostActivity.this, Tools.sharePreferencesUserKey, Tools.UserPhonekey);
		edit_phone.setText(phoneString);
		
		
		newsController = new NewsController();
		
		Bundle data=getIntent().getExtras();
		if(data==null)
			finish();
		else
		{
			longti = (float)data.getDouble("longti");
			lati=(float)data.getDouble("lati");
			
		}
		
		btn_browser.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                 
                startActivityForResult(i, RESULT_LOAD_IMAGE);
			}
		});
		
		btn_submit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String contenText= edit_content.getText().toString().trim();
				String titleText= edit_title.getText().toString().trim();
				String phoneText = edit_phone.getText().toString().trim();
				
				if(!contenText.equals("") && !titleText.equals("") && !phoneText.equals(""))
				{
				
				String dateText=createUploadDate();
				String username = Tools.loadSavedPreferences(PostActivity.this, Tools.sharePreferencesUserKey, Tools.UserEmailkey);
				
				String []imgArray={imgFilePath};
				final News news=new News(0,username,contenText ,titleText , topic, city,phoneText,longti,lati,dateText ,dateText , dateText+"/img1.jpg",imgArray);
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						
						final boolean result = newsController.addNewsToServer(news);
						runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								if(result)
								{
									//success
									Toast.makeText(PostActivity.this, getString(R.string.success_request), Toast.LENGTH_LONG).show();
									edit_content.setText("");
									edit_title.setText("");
									
								}
								else
								{
									Toast.makeText(PostActivity.this, getString(R.string.request_error_title), Toast.LENGTH_LONG).show();
								}
							}
						});
					}
				}).start();
				
				}
				else
				{
					Toast.makeText(PostActivity.this, getString(R.string.please_input_data), Toast.LENGTH_LONG).show();
				
				}
			}
		});
		
		sp_topic_choice.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
				Toast.makeText(parent.getContext(), 
						"OnItemSelectedListener topic : " + parent.getItemAtPosition(pos).toString(),
						Toast.LENGTH_SHORT).show();
				topic = parent.getItemAtPosition(pos).toString();
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				
			}
		});
		sp_city_choice.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
				// TODO Auto-generated method stub
				Toast.makeText(parent.getContext(), 
						"OnItemSelectedListener city : " + parent.getItemAtPosition(pos).toString(),
						Toast.LENGTH_SHORT).show();
				city = parent.getItemAtPosition(pos).toString();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});
	}
	
	private String createUploadDate()
	{
		String result="";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		result = sdf.format(new Date());
		return result;
	}
	
	 @Override
	    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	        super.onActivityResult(requestCode, resultCode, data);
	         
	        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
	            Uri selectedImage = data.getData();
	            String[] filePathColumn = { MediaStore.Images.Media.DATA };
	 
	            Cursor cursor = getContentResolver().query(selectedImage,
	                    filePathColumn, null, null, null);
	            cursor.moveToFirst();
	 
	            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
	            imgFilePath = cursor.getString(columnIndex);
	            cursor.close();
	             
	        }
	     
	     
	    }
}
